Java while loop

In this tutorial, we will learn about the while loop and do while loop syntax, along with working examples and an explanation of the output of examples used.

while loop

In Java, while loop is used to execute a block of statements in a loop manner based on the condition of the loop. Consider an example of cooking vegetables on a stove, we will be checking few times whether its properly boiled or need to cook some more and will be checking until its boiled nothing loop of testing until its cooked. To handle this kind of requirement, looping is the best suit to fulfil it.

Syntax:

while(condition) {
//statements inside a while loop
}

Example:

CopiedCopy Code
public class WhileLoopExample {
	public static void main(String[] args) {
		int i=1;
			while(i<=5)
			{
			System.out.println("Printing number of iteration count : "+i);
			i++;
			}
	}
}

Output:

Printing number of iteration count : 1
Printing number of iteration count : 2
Printing number of iteration count : 3
Printing number of iteration count : 4
Printing number of iteration count : 5

After executing example program, we will see above lines getting printed. Following is the explanation of the example program and its output.

  1. We have declared a variable i of int type with value as 1.
  2. In the while loop, we passed the condition. Condition checks i value is less than or equals to 5.
  3. When condition satisfies, will enters the loop of while.
  4. Inside a loop a print statement will be executed
  5. After print statement, i variable is incremented by 1 using ++
  6. Again, loop condition evaluates and continues to execute until the condition not satisfies.
  7. Condition will not be satisfied when i value becomes 6.

While loop more commonly used for iterating JDBC result sets and lists, as it requires to check only the next element is available or not.

do while loop

do while loop will complete first execution without condition evaluation from second execution onwards checks the condition. In other words, loop gets executed one time without checking condition and condition may or may not be satisfied.

Syntax:

do {
//inside loop
}while(condition);

Example:

CopiedCopy Code
public class DoWhileExample {
	public static void main(String[] args) {
		int number=1;
		do{
		     System.out.println("Value of the number: "+number);
		}while(number!=1);
	}
}

Output:

Value of the number: 1

After executing example above line gets printed, explanation and output of the example as follows.

  1. We have initialized a variable i of int type with value 1.
  2. Written a do while loop with condition value of i should not be 1.
  3. i value is 1 and condition is not satisfied.
  4. do while loop one execution is completed without satisfying condition.
  5. For second execution, condition should satisfy.
  6. Condition is not satisfied and loop is exited.

Conclusion:

In this tutorial, we have learned the syntax of while and do while along with working examples.